package com.bmob.lover.ui.adapter

import android.app.Activity
import android.content.res.Configuration
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.theone.common.ext.goneViews
import com.theone.common.ext.showViews
import com.bmob.lover.R
import com.bmob.lover.app.widget.SampleCoverVideo
import com.bmob.lover.data.model.bean.Lover
import com.bmob.lover.data.model.bean.TheFile
import com.bmob.lover.databinding.ItemLoverBinding
import com.luck.picture.lib.config.SelectMimeType
import com.theone.mvvm.core.app.util.FileDirectoryManager
import java.io.File

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-04-22 14:06
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
class LoverAdapter : BaseBmobDiffAdapter<Lover, ItemLoverBinding>(R.layout.item_lover) {

    companion object {
        const val TAG = "LoverAdapter"
    }

    private var curPlayer: StandardGSYVideoPlayer? = null
    private var orientationUtils: OrientationUtils? = null
    private var isPlay = false
    private var isFull = false
    private val isFirstInit = true

    override fun convert(holder: BaseDataBindingHolder<ItemLoverBinding>, item: Lover) {
        super.convert(holder, item)
        holder.dataBinding?.run {
            goneViews(nineGrid, videoPlayer)
            val urls = item.urls
            var files = mutableListOf<TheFile>()
            if (!item.attachments.isNullOrEmpty()) {
                files = Gson().fromJson(
                    item.attachments,
                    object : TypeToken<List<TheFile?>?>() {}.type
                )
            } else if (!urls.isNullOrEmpty()) {
                for (url in urls) {
                    files.add(TheFile(path = url, mThumbnail = url))
                }
            }
            if (files.size > 0) {
                if (item.type == SelectMimeType.TYPE_VIDEO) {
                    showViews(videoPlayer)
                    initVideoPlayer(videoPlayer, files[0], holder.adapterPosition)
                } else {
                    showViews(nineGrid)
                    nineGrid.setUrlList(files)
                }
            }
        }
    }


    private fun initVideoPlayer(
        coverVideo: SampleCoverVideo,
        file: TheFile,
        position: Int
    ) {
        with(coverVideo) {
            isRotateViewAuto = false
            isLockLand = false
            playTag = TAG
            isAutoFullWithSize = true
            isReleaseWhenLossAudio = false
            isShowFullAnimation = true
            setIsTouchWiget(false)
            //循环
            isLooping = true
            isNeedLockFull = false

            //coverVideo.setSpeed(2);
            playPosition = position
            setVideoAllCallBack(object : GSYSampleCallBack() {
                override fun onClickStartIcon(url: String, vararg objects: Any) {
                    super.onClickStartIcon(url, *objects)
                }

                override fun onPrepared(url: String, vararg objects: Any) {
                    super.onPrepared(url, *objects)
                    val full: Boolean = coverVideo.currentPlayer.isIfCurrentIsFullscreen
                    if (!coverVideo.currentPlayer.isIfCurrentIsFullscreen) {
                        GSYVideoManager.instance().isNeedMute = true
                    }
                    curPlayer = objects[1] as StandardGSYVideoPlayer
                    isPlay = true
                    if (getListNeedAutoLand()) {
                        //重力全屏工具类
                        initOrientationUtils(coverVideo, full)
                        onPrepared()
                    }
                }

                override fun onQuitFullscreen(url: String, vararg objects: Any) {
                    super.onQuitFullscreen(url, *objects)
                    isFull = false
                    //                GSYVideoManager.instance().setNeedMute(true);
                    if (getListNeedAutoLand()) {
                        onQuitFullscreen()
                    }
                }

                override fun onEnterFullscreen(
                    url: String,
                    vararg objects: Any
                ) {
                    super.onEnterFullscreen(url, *objects)
                    GSYVideoManager.instance().isNeedMute = false
                    isFull = true
                    currentPlayer.titleTextView.text = objects[0] as String
                }

                override fun onAutoComplete(url: String, vararg objects: Any) {
                    super.onAutoComplete(url, *objects)
                    curPlayer = null
                    isPlay = false
                    isFull = false
                    if (getListNeedAutoLand()) {
                        onAutoComplete()
                    }
                }
            })
            setUpLazy(
                file.path,
                true,
                File(FileDirectoryManager.getCachePath()),
                null,
                ""
            )
            loadCoverImage(file)

        }

    }

    /**
     * 全屏幕按键处理
     */
    private fun resolveFullBtn(standardGSYVideoPlayer: SampleCoverVideo) {
        if (getListNeedAutoLand() && orientationUtils != null) {
            resolveFull()
        }
        standardGSYVideoPlayer.startWindowFullscreen(context, false, true)
    }

    fun clearCache() {
        if (curPlayer != null) {
            curPlayer!!.currentPlayer.clearCurrentCache()
        }
    }

    fun isFull(): Boolean {
        return isFull
    }

    /**************************支持全屏重力全屏的部分**************************/

    /**************************支持全屏重力全屏的部分 */
    /**
     * 列表时是否需要支持重力旋转
     *
     * @return 返回true为支持列表重力全屏
     */
    fun getListNeedAutoLand(): Boolean {
        return false
    }

    private fun initOrientationUtils(
        standardGSYVideoPlayer: StandardGSYVideoPlayer,
        full: Boolean
    ) {
        orientationUtils = OrientationUtils(context as Activity?, standardGSYVideoPlayer)
        //是否需要跟随系统旋转设置
        //orientationUtils.setRotateWithSystem(false);
        orientationUtils?.isEnable = false
        orientationUtils?.isLand = if (full) 1 else 0
    }

    private fun resolveFull() {
        if (getListNeedAutoLand()) {
            //直接横屏
            orientationUtils?.resolveByClick()
        }
    }

    private fun onQuitFullscreen() {
        orientationUtils?.backToProtVideo()
    }

    fun onAutoComplete() {
        orientationUtils?.isEnable = false
        orientationUtils?.releaseListener()
        orientationUtils = null
        isPlay = false
    }

    fun onPrepared() {
        if (orientationUtils == null) {
            return
        }
        //开始播放了才能旋转和全屏
        orientationUtils?.setEnable(true)
    }

    fun onConfigurationChanged(
        activity: Activity?,
        newConfig: Configuration?
    ) {
        //如果旋转了就全屏
        if (isPlay && curPlayer != null && orientationUtils != null) {
            curPlayer!!.onConfigurationChanged(activity, newConfig, orientationUtils, false, true)
        }
    }

    fun getOrientationUtils(): OrientationUtils? {
        return orientationUtils
    }


    fun onBackPressed() {
        orientationUtils?.backToProtVideo()
    }

    fun exitFullScreen() {
        curPlayer?.onBackFullscreen()
    }

    fun onDestroy() {
        if (isPlay) {
            curPlayer?.currentPlayer?.release()
        }
        orientationUtils?.releaseListener()
        orientationUtils = null
    }

}